import * as CryptoJS from "crypto-js"
import * as qiniu from "qiniu-js"
import JSZip from "jszip";
import Moment from "moment";
import FileSaver from "file-saver"


export const DOWNLOAD_TYPES = {
  CREATIVE_NAME : 4,
  ORIGIN_NAME : 2,
  WATERMARK_CREATIVE : 1,
  WATERMARK_ORIGIN : 3
}

export const upload_file = (upload_file, progress_callback,
                            complete_callback, error_callback) => {
  let fileData = getFileData(upload_file)
  let callback = {
    next(res) {
      if (progress_callback)
        progress_callback(res.total.percent)
    },
    error(err) {
      if (error_callback)
        error_callback(err)
    },
    complete(res) {
      if (complete_callback)
        complete_callback(upload_file, 'http://' + fileData.server + '/' + res.key)
    }
  }
  let uploader = uploadQiniuCloud(upload_file, fileData)
  uploader.subscribe(callback)
}

export function getQiniuUploadToken(accessKey, secureKey, uploadJObj) {
  let uploadJson = JSON.stringify(uploadJObj)
  if(uploadJson !== undefined && uploadJson !== null && uploadJson !== ""){
    let encodedPutPolicy = btoa(uploadJson)
    let hmacSha1 = CryptoJS.HmacSHA1(encodedPutPolicy, secureKey);
    let sign = CryptoJS.enc.Base64.stringify(hmacSha1)
    let encodedSign = safe64(sign)
    return accessKey + ":" + encodedSign + ":" + encodedPutPolicy
  }
  return ""
}

export function genDefaultUploadPolicy(bucket, deadline) {
  return {
    "scope": bucket,
    "deadline": new Date(new Date().getTime() + deadline).getTime(),
  }
}

export function qiniuEasyWatermarkWithImage(logo, target, domain) {
  let watermark = {
    mode: 1,
    image: logo,
    dissolve: 50,
    gravity: "SouthEast",
    dx: 50,
    dy: 50
  }
  return qiniuWatermarkWithImage(watermark, target, domain)
}


export function qiniuWatermarkWithImage(watermarkObj, target, domain) {
  return qiniu.watermark(watermarkObj, target, domain)
}

export function safe64(base64) {
    base64 = base64.replace(/\+/g, "-");
    base64 = base64.replace(/\//g, "_");
    return base64;
}

export function getFileData(file) {
  let fileType = creativeType(file);
  return {
    server: fileType === 'image' ? 'image-origin-bucket.ninesword.com' :
      'video-origin-bucket.ninesword.com',
    bucket: fileType === 'image' ? 'ads4each-image-origin' : 'ads4each-video-origin',
    name: Math.floor((Math.random() + Math.floor(Math.random() * 9 + 1)) * 10 ** (13 - 1)) + '',
    localName: file.file.name,
  }
}

export function getFileDataWithKey(file, key) {
  let fileType = creativeType(file);
  return {
    server: fileType === 'image' ? 'image-origin-bucket.ninesword.com'
        : fileType === 'video' ? 'video-origin-bucket.ninesword.com' : 'ads4each-attachments',
    bucket: fileType === 'image' ? 'ads4each-image-origin'
      : fileType === 'video' ? 'ads4each-video-origin' : 'ads4each-attachments',
    name: key,
    localName: file.file.name,
  }
}

//上传七牛云
export function uploadQiniuCloud(file, fileData) {
  // 配置
  const config = {
    forceDirect: false,
    chunkSize: 4,
    retryCount: 99
  };
  let qiniuClient = {
    access_key_id: "4K8rpbd6szJZXszowt741vofKRLlMjkgwYAVhfJt",
    secret_access_key: "UAb4L4S-QdTVWumrMHL2uapKtPgsr_-_IstlydVb",
    bucket: fileData.bucket
  }
  let key = fileData.name + "."+fileData.localName.split('.')[fileData.localName.split('.').length - 1].split('?')[0]
  let putPolicy = genDefaultUploadPolicy(qiniuClient.bucket, 3600000)
  let uploadToken = getQiniuUploadToken(qiniuClient.access_key_id,
    qiniuClient.secret_access_key, putPolicy)
  return qiniu.upload(file.file, key, uploadToken, null, config)
}

function creativeType(file) {
  if (file.file.type.startsWith("image"))
    return "image"
  if (file.file.type.startsWith("video"))
    return "video"
}

export function DownloadFileWithZip(filesMap, downloadOption, loadingElement){
  const promise = downloadUrl(downloadOption === 1||downloadOption === 3 ? filesMap[0].waterUrl +
    `?${Math.floor(Math.random() * 99999999)}` : filesMap[0].creativeUrl + `?${Math.floor(Math.random() * 99999999)}`)
    .then(res => {
      loadingElement.close();
      let blob = new Blob([res])
      FileSaver.saveAs(blob, downLoadName(filesMap[0],downloadOption) +
        '.' + filesMap[0].localFilename.split('.')[filesMap[0].localFilename.split('.').length - 1]);

      this.$refs.crud.toggleSelection();

    }).catch(error => {
      if (error){
        let msg = '素材下载失败，请重试！'
        loadingElement.close()
        return msg
      }
    })
  return null
}

export function BatchDownloadFilesWithZip(filesMap, downloadOption, loadingElement, selectEl, offerList, offer){
  if(filesMap.length === 0){
    console.log("至少选择一项数据")
  }
  let zip = new JSZip();
  let obj = {};
  let promises = [];
  filesMap.map((item, index) => {
    const promise = downloadUrl(downloadOption === DOWNLOAD_TYPES.WATERMARK_CREATIVE || downloadOption === DOWNLOAD_TYPES.WATERMARK_ORIGIN
      ? item.waterUrl + `?${Math.floor(Math.random() * 99999999)}` : item.creativeUrl + `?${Math.floor(Math.random() * 99999999)}`).then(res => {
      zip.file(downLoadName(filesMap[index],downloadOption) +
        '.' + filesMap[index].localFilename.split('.')[filesMap[index].localFilename.split('.').length - 1],
        res, {binary: true}); //
      obj [filesMap[index].name + '.' + filesMap[index].localFilename.split('.')[1]] = res;// 逐个添
    })
    promises.push(promise);
  })
  Promise.all(promises).then(() => {
    zip.generateAsync({type: "blob"}).then(res => {
      // 生成二进制流
      FileSaver.saveAs(res, offerList[offerList.findIndex(item => item.id === offer)].name + Moment(new Date()).format('YYYYMMDDhhmmss')); // 利用file-saver保存文件,可以改成自己想要的压缩包名称
      loadingElement.close();
      filesMap = [];
      selectEl.toggleSelection();
    });
  }).catch((e) => {
    loadingElement.close();
    let msg = '素材下载失败，请重试！'
    console.error(e);
    return msg
  });
  return null
}

export function downloadUrl(url){
  return new Promise((resolve,reject) => {
    if (!url.startsWith('http')) {
      return;
    }
  })
}

export function downLoadName(selectFile, downloadOption){
  let name;
  if (selectFile.originCreativeId && selectFile.originCreativeId !== '') {
    name = selectFile.localFilename;
  } else if(downloadOption === 2||downloadOption ===3){
    name = selectFile.localFilename;
  }
  else {
    name = selectFile.name;
  }

  let index = name.lastIndexOf(".");
  if (index > 0) {
    return name.substring(0, index);
  } else {
    return name;
  }
}

export function parseUrlObj(url){
  if(!url.startsWith("http")){
    return null;
  }
  let urlArr = url.split("://")
  if(urlArr.length < 2){
    return null;
  }
  let hostAndPath = urlArr[1]
  let hostAndPathArr = hostAndPath.split("/")
  if(hostAndPathArr.length < 1){
    return null;
  } else if(hostAndPathArr.length === 1){
    return {
      protocol:urlArr[0],
      host:hostAndPathArr[0],
      path:""
    }
  } else {
    return {
      protocol:urlArr[0],
      host:hostAndPathArr[0],
      path:hostAndPathArr[1]
    }
  }
}

export function getCrossUrl(url){
  let urlObj = parseUrlObj(url)
  if(urlObj === null){
    return null;
  }
  if(urlObj.host === "image-origin-bucket.ninesword.com"){
    return "/access-creative-image" + urlObj.path
  }
  if(urlObj.host === "video-origin-bucket.ninesword.com"){
    return "/access-creative-video" + '/' + urlObj.path
  }
  return null
}

